package pub.guoxin.oops.utils;

import com.google.common.collect.Maps;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * Created by guoxin on 18-3-15.
 */
public class ParseKeyword {

    private static final String PREFIX = "${";

    private static final String SUFFIX = "}";

    private static final String S = "%s";

//    private static final String REGEX = "^(\\$\\()&";

    /**
     * 解析占位符${}
     *
     * @param pattern
     * @param param
     * @return
     * @throws VariableNotFoundException
     */
    public static String parse(String pattern, Map<String, String> param) {
        Objects.requireNonNull(pattern, "\"pattern\" not null!");
        Set<Map.Entry<String, String>> entries = param.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if (!pattern.contains(PREFIX)) {
                return pattern;
            }
            String name = entry.getKey();
            String value = entry.getValue();

            String format = String.format(PREFIX + S + SUFFIX, name);
            pattern = pattern.replace(format, value);

        }
        return pattern;
    }

    public static void main(String[] args) {
//        boolean matches = Pattern.matches(REGEX, "aaaa${lll}aaaaa${lll}aaaaa${bbb}aaaaaaaaaaa");
        HashMap<String, String> map = Maps.newHashMap();
        map.put("code", "111222333");
        map.put("lala", "i love you");
        map.put("la1la", "you love me");
        String parse = parse("fjdsklajf${code}321${code}312${la1la}312${lala}312", map);
        System.out.println(parse);
    }


}

class VariableNotFoundException extends Exception {
    private static final long serialVersionUID = -999445962002219791L;
}